<template>
  <div>
    <el-form label-position="right" label-width="150px" :model="writerForm" :rules="rules">
      <el-form-item label="数据库源：" prop="datasourceId">
        <el-select
          v-model="writerForm.datasourceId"
          filterable
          style="width: 300px "
          @change="wDsChange"
        >
          <el-option
            v-for="item in wDsList"
            :key="item.id"
            :label="item.datasourceName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-show="dataSource==='postgresql' || dataSource==='oracle' ||dataSource==='sqlserver'" label="Schema：" prop="tableSchema">
        <el-select v-model="writerForm.tableSchema" filterable style="width: 300px" @change="schemaChange">
          <el-option
            v-for="item in schemaList"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="数据库表名：" prop="tableName">
        <el-select
          v-model="selectedTableName"
          disabled
          style="width: 300px "
        >
          <el-option
            v-for="item in tableOptions"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <div style="margin: 5px 0 " />
    </el-form>
  </div>
</template>

<script>
import * as dsQueryApi from '@/api/metadata-query'
import { list as jdbcDsList } from '@/api/datax-jdbcDatasource'
import Bus from '../busWriter'
export default {
  name: 'RDBMSWriterRDBMSWriter',
  data() {
    return {
      jdbcDsQuery: {
        current: 1,
        size: 200,
        ascs: 'datasource_name'
      },
      wDsList: [],
      schemaList: [],
      fromTableName: '',
      fromColumnList: [],
      wTbList: [],
      dataSource: '',
      createTableName: '',
      writerForm: {
        datasourceId: undefined,
        tableName: '',
        columns: [],
        checkAll: false,
        isIndeterminate: true,
        preSql: '',
        postSql: '',
        ifCreateTable: false,
        tableSchema: ''
      },
      rules: {
        datasourceId: [{ required: true, message: 'this is required', trigger: 'change' }],
        // tableName: [{ required: true, message: 'this is required', trigger: 'change' }],
        tableSchema: [{ required: true, message: 'this is required', trigger: 'change' }]
      },
      tableOptions: [],
      selectedTableName: ''
    }
  },
  watch: {
    'writerForm.datasourceId': function(oldVal, newVal) {
      if (this.dataSource === 'postgresql' || this.dataSource === 'oracle' || this.dataSource === 'sqlserver') {
        this.getSchema()
      } else {
        this.getTables('rdbmsWriter')
      }
    }
  },
  created() {
    this.getJdbcDs()
  },
  methods: {
    // 获取可用数据源
    getJdbcDs() {
      this.loading = true
      jdbcDsList(this.jdbcDsQuery).then(response => {
        const { records } = response
        this.wDsList = records
        this.loading = false
      })
    },

    getSchema() {
      const obj = {
        datasourceId: this.writerForm.datasourceId
      }
      dsQueryApi.getTableSchema(obj).then(response => {
        this.schemaList = response
      })
    },
    // schema 切换
    schemaChange(e) {
      this.writerForm.tableSchema = e
      const readerTableName = this.$parent.getReaderData().readerForm.customTableName
      if (readerTableName) {
        this.writerForm.tableName = readerTableName
        this.selectedTableName = readerTableName
      } else {
        this.writerForm.tableName = ''
        this.selectedTableName = ''
      }
    },
    wDsChange(e) {
      // 清空
      this.writerForm.datasourceId = e
      this.wDsList.find((item) => {
        if (item.id === e) {
          this.dataSource = item.datasource
        }
      })

      Bus.dataSourceId = e
      this.$emit('selectDataSource', this.dataSource)

      // 切换数据源后重新加载表名
      const readerTableName = this.$parent.getReaderData().readerForm.customTableName
      if (readerTableName) {
        this.writerForm.tableName = readerTableName
        this.selectedTableName = readerTableName
        this.tableOptions = [readerTableName] // 表名只显示一个选项
      } else {
        this.writerForm.tableName = ''
        this.selectedTableName = ''
        this.tableOptions = []
      }
    },

    wHandleCheckAllChange(val) {
      this.writerForm.columns = val ? this.fromColumnList : []
      this.writerForm.isIndeterminate = false
    },
    wHandleCheckedChange(value) {
      const checkedCount = value.length
      this.writerForm.checkAll = checkedCount === this.fromColumnList.length
      this.writerForm.isIndeterminate = checkedCount > 0 && checkedCount < this.fromColumnList.length
    },
    getData() {
      if (Bus.dataSourceId) {
        this.writerForm.datasourceId = Bus.dataSourceId
      }
      return this.writerForm
    },
    getTableName() {
      return this.fromTableName
    },
    createTable() {
      const readerForm = this.$parent.getReaderData()
      const readerColumns = readerForm.rColumnList.filter(item =>
        readerForm.readerForm.columns.includes(item.columnName)
      )
      const selectedTableName = readerForm.readerForm.customTableName

      if (!selectedTableName) {
        this.$message.error('目标表名不能为空')
        return
      }

      const obj = {
        datasourceId: this.writerForm.datasourceId,
        tableSchema: this.writerForm.tableSchema,
        tableName: selectedTableName,
        tableComment: readerForm.readerForm.tableComment,
        tagId: readerForm.readerForm.selectedTags,
        columns: readerColumns.map(item => ({
          columnName: item.columnName,
          typeClassName: item.typeClassName,
          columnDes: item.columnDes
        }))
      }

      dsQueryApi.createTable(obj).then(response => {
        if (response) {
          debugger
          this.$notify({
            title: 'Success',
            message: '创建表成功',
            type: 'success',
            duration: 2000
          })
        } else {
          this.$notify({
            title: 'Error',
            message: response.msg || '创建表失败',
            type: 'error',
            duration: 2000
          })
        }
      }).catch(error => {
        console.error('创建表失败:', error)
        this.$notify({
          title: 'Error',
          message: '创建表时发生错误',
          type: 'error',
          duration: 2000
        })
      })
    }

  }
}
</script>
